/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package armazemseujose.model;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.Scanner;

/**
 *
 * @author BRUNA
 */
public class listaItens {

    ArrayList<Item> itens = new ArrayList();

    public listaItens() throws FileNotFoundException {
        lerArquivoItem();
    }

    public void add(Item item) throws IOException {
        itens.add(item);
        salvaArquivoItem(item);
    }
    
    public void salvaArquivoItem(Item i) throws IOException {
        File dir = new File(".");
        File arq = new File(dir, "itens.txt");
        FileWriter fileWriter = new FileWriter(arq, true);
        PrintWriter printWriter = new PrintWriter(fileWriter);
        printWriter.println(i.getNome() + "|" + i.getPrecoVenda());
        printWriter.flush();
    }
    
    public void lerArquivoItem() throws FileNotFoundException {
        Scanner scanner = new Scanner(new FileReader("itens.txt"))
                .useDelimiter("\\||\\n");
        while (scanner.hasNext()) {
            String nome = scanner.next();
            String preco = scanner.next();
            String precoVenda = preco.substring(0, preco.length() - 1);
            double i = Double.parseDouble(precoVenda);
            itens.add(new Item(nome, i));
        }
    }

    public Item procuraItem(String nome) {
        for (Item i : itens) {
            String a = i.getNome();
            if (a.equalsIgnoreCase(nome)) {
                return i;
            }
        }
        return null;
    }
}
